import {dataURLtoFile} from '@/utils/64batatoFile'
import request,{axios} from '@/utils/request'
import lrz from 'lrz'
import html2Canvas from 'html2canvas'
import domtoimage from 'dom-to-image';
let userAgent
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
  userAgent = true
}else{
  userAgent=false
}
const http = window.location.href.slice(0, window.location.href.indexOf('/site'))
export async function upFile(name,data,domid) {
    let formData = new FormData
    if(data){
        Object.keys(data).map(item=>{
            formData.append(item,data[item])
        })
    }
    let nodeid = document.getElementById(domid)
    // if(http.indexOf('tjy')!=-1){
    //     alert(nodeid,domid,'测试使用')
    // }
    var newDom = document.createElement('div')
    newDom.appendChild(nodeid.cloneNode(true))
    var domImgid = newDom.childNodes[0]
    newDom.style.position = 'absolute'
    newDom.style.zIndex = '-10000'
    domImgid.style.position = 'relative'
    // domImgid.querySelector('img')
    let iosdomid = domImgid
    document.body.appendChild(newDom)
    // console.log(newDom,nodeid.getElementsByTagName('img')[1].src,'pppp');
    // if(domid == 'DomImgfwxy'){
    //     iosdomid = domImgid
    //     await domtoimage.toPng(iosdomid)
    // }else{
    //     iosdomid = domImgid
    // }
    
    // if(location.href.includes('adminApply')&&domid == 'DomImgjkcns'){
    //     console.log(nodeid,'789');
    //     iosdomid = nodeid
    //     // await domtoimage.toPng(nodeid)
    // }
    // for (const key in domImgid.getElementsByTagName('img')) {
    //     if (Number(key)||key==0) {
    //         if(domImgid.getElementsByTagName('img')[key].src.includes('http')){
    //             await ImgUrltoBase(domImgid.getElementsByTagName('img')[key].src).then(res=>{
    //                 domImgid.getElementsByTagName('img')[key].src = res
    //             }).catch((err)=>{
    //                 console.error(err,'77777');
    //             })
    //         }
    //     }
    // }
    // newDom.querySelector('img').map(item=>{
    //     ''.includes()
    //     if(item.src.includes('http')){
    //         item.src = ImgUrltoBase(item.src)
    //     }
    // })
    // if(process.env.NODE_ENV === 'development'){
    //     for (const key in domImgid.getElementsByTagName('img')) {
    //         if (key==0||Number(key)) {
    //             const item = domImgid.getElementsByTagName('img')[key];
    //             item.crossOrigin='Annoymous'
    //             item.src= '/img/storage'+item.src.split('/storage')[1]
    //         }
    //     }
    // }
   
    let  baseUrl=process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API :window.location.href.slice(0, window.location.href.indexOf('/site'))
    
        return new Promise((resolve,reject)=>{
            // if(userAgent){
            //     html2Canvas(nodeid, {
            //         allowTaint: true,
            //         useCROS: true,
            //         height: nodeid.offsetHeight || nodeid.scrollHeight || nodeid.clientHeight,
            //         width: nodeid.offsetWidth || nodeid.scrollWidth || nodeid.clientWidth,
            //         x:0,
            //         y:0,
            //     }).then(function (canvas) {
            //         let pageData = canvas.toDataURL('image/jpeg', 1.0)
            //         lrz(pageData).then(res=>{
            //             let obj = dataURLtoFile(res.base64,name+'.jpg')
            //             formData.append('img',obj)
            //             request(
            //                 {
            //                     url:baseUrl+'/admin/MemberApply/upload',
            //                     method:'post',
            //                     data: formData
            //                 }
            //             ).then(res=>{
            //                 resolve(res)
            //             }).catch((err)=>{
            //                 reject(err)
            //             })
            //         })
            //     })
            // }else{
            // }
            
            domtoimage.toPng(iosdomid)
            .then(function (dataUrl) {
                document.body.removeChild(newDom)
                ImgUrltoBase(dataUrl).then(src=>{
                    lrz(src,{quality:0.8}).then(res=>{
                        let obj = dataURLtoFile(res.base64,name+'.jpg')
                        formData.append('img',obj)
                        request(
                            {
                                url:baseUrl+'/admin/MemberApply/upload',
                                method:'post',
                                data: formData
                            }
                        ).then(res=>{
                            resolve(res)
                        }).catch((err)=>{
                            reject(err)
                        })
                    })
                })
            })
            .catch(function (error) {
                document.body.removeChild(newDom)
                console.error('元素转换错误!', error);
            });
        })
   
}
export function upFileqm(imgUrl,name,data) {
    let formData = new FormData
    if(data){
        Object.keys(data).map(item=>{
            formData.append(item,data[item])
        })
    }
    let  baseUrl=process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API :window.location.href.slice(0, window.location.href.indexOf('/site'))
    return new Promise((resolve,reject)=>{
        let obj = dataURLtoFile(imgUrl,name+'.png')
        // let list = [obj]
        formData.append('img',obj)
        request(
            {
                url:baseUrl+'/admin/MemberApply/upload',
                method:'post',
                data: formData
            }
        ).then(res=>{
            resolve(res)
        }).catch((err)=>{
            reject(err)
        })
        // lrz(imgUrl,{quality:0.8}).then(res=>{
        // })
    })
}

//判断照片角度是否正确
export function isNeedFixPhoto(file) {
    const EXIF = require("exif-js");
    let _this = this;
    // _this.$dialog.confirm({
    //   title:'提示',
    //   message:JSON.stringify(file),
    //   showCancelButton:true,
    // })
    return new Promise(function (resolve, reject) {
        if (EXIF) {
        EXIF.getData(file, function () {
            console.log(1200);
          var Orientation = EXIF.getTag(this, "Orientation");
          // _this.$dig.error(JSON.stringify(EXIF.getAllTags(this)))

          if (Orientation && Orientation != 1) {
            //图片角度不正确
            resolve({ flag: true, Orientation: Orientation });
          } else {
            //不需处理直接上传
            resolve({ flag: false, Orientation: Orientation });
          }
        });
      } else {
        resolve(null);
      }
    });
}



function callFunction(img) {
    let canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    return new Promise((resolve, reject) => {
        img.onload = function() {
          canvas.height = img.height
          canvas.width = img.width
          ctx.fillStyle = '#fff' // canvas背景填充颜色默认为黑色
          ctx.fillRect(0,0,img.width,img.height)
          ctx.drawImage(img, 0, 0) // 参数可自定义
          const dataURL = canvas.toDataURL('image/png', 1) // 获取Base64编码
          resolve(dataURL)
          canvas = null // 清除canvas元素
        //   img = null // 清除img元素
        }
        img.onerror = function() {
            reject('错误')
        }
      })
}
//url转file
// export function ImgUrltoFile(imageUrl,name){
//     let a = ''
//     getImageFileFromUrl(imageUrl, name, function (file) {
//         // file = file; //获取file对象
//         a = file
//     });
//     return a
// } 
// 根据路径返回file
export async function ImgUrltoBase(imageUrl) {
    let img = new Image()
    img.crossOrigin = 'Anonymous' // 解决Canvas.toDataURL 图片跨域问题
    img.src = imageUrl
    // document.body.appendChild(img)
    return callFunction(img)
}